package com.kchouse;


import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps2d.AMapUtils;
import com.amap.api.maps2d.model.LatLng;
import com.kchouse.bean.BannerItem;
import com.kchouse.bean.CashCouponItem;
import com.kchouse.bean.CouponItem;
import com.kchouse.bean.DirItem;
import com.kchouse.bean.MerchantItem;
import com.kchouse.bean.OrderEvaItem;
import com.kchouse.bean.OrderItem;
import com.kchouse.bean.PrestoreItem;
import com.kchouse.common.API;
import com.kchouse.common.BaseFragment;
import com.kchouse.common.MyHttpCycleContext;
import com.kchouse.common.MyUtils;
import com.kchouse.homepage.CouponDetailsActivity;
import com.kchouse.homepage.GoodsDetailsActivity;
import com.kchouse.homepage.PrestoreDetailsActivity;
import com.kchouse.mine.LoginPhoneActivity;
import com.kchouse.mine.MyOrderItemActivity;
import com.kchouse.myadapter.OrderAllAdapter;
import com.kchouse.myadapter.OrderEvaAdapter;
import com.kchouse.myadapter.PrestoreAdapter;
import com.kchouse.myadapter.SuitAdapter;
import com.kchouse.myadapter.UnionAdapter;
import com.kchouse.union.MerchantDetailsActivity;
import com.kchouse.view.BannerLoader;
import com.kchouse.view.ProgressView;
import com.kchouse.common.ToastUtils;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import java.text.DecimalFormat;
import java.util.ArrayList;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import me.fangx.haorefresh.HaoRecyclerView;
import me.fangx.haorefresh.LoadMoreListener;


/**
 * A simple {@link Fragment} subclass.
 */
public class ListFragment extends BaseFragment {


    private String data;
    private int size;
    private String name;
    private View view;
    private ListView lv_item;
    private LayoutInflater inflater;
    private CheckBox cb_1;
    private CheckBox cb_2;
    private View ll_item;
    private View ll_item2;
    private View headerview;
    private ArrayList<BannerItem> listbanner = new ArrayList<>();
    private ArrayList<MerchantItem> listmerchant = new ArrayList<>();
    private ArrayList<OrderItem> listorder = new ArrayList<>();
    private ArrayList<OrderEvaItem> listordereva = new ArrayList<>();
    private ArrayList<CashCouponItem> listcashcoupon = new ArrayList<>();
    private ArrayList<DirItem> listdir = new ArrayList();//联盟活动
    private ArrayList<DirItem> listsuit = new ArrayList();//联盟套餐
    private ArrayList<CouponItem> listcoupon = new ArrayList<>();//联盟优惠券
    private ArrayList<PrestoreItem> listprestore = new ArrayList<>();//联盟预存

    private EditText et_search;

    private UnionAdapter unionAdapter;

    private HaoRecyclerView hao_recycleview;
    private int page = 1;
    private int totalCount;//总个数
    private Intent intent = new Intent();
    private OrderAllAdapter orderAdapter;
    private OrderEvaAdapter orderevaAdapter;
    private boolean isLogin = false;
    private boolean issearch = false;//是否曾今搜索过
    private SuitAdapter suitAdapter;
    private PrestoreAdapter prestoreAdapter;


    public ListFragment() {
        // Required empty public constructor
    }

    @SuppressLint("ValidFragment")//默认
    public ListFragment(int size, String name) {
        this.size = size;
        this.name = name;
    }

    @SuppressLint("ValidFragment")//数据 名称
    public ListFragment(String data, String name) {
        this.data = data;
        this.name = name;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        if (view == null) {
            this.inflater = inflater;
            view = inflater.inflate(R.layout.fragment_list, null);
            intiData();
            intiView();
        }

        return view;
    }

    private void intiData() {

    }

    private void intiView() {
        lv_item = (ListView) view.findViewById(R.id.lv_item);
        ll_item = view.findViewById(R.id.ll_item);
        ll_item2 = view.findViewById(R.id.ll_item2);
        headerview = inflater.inflate(R.layout.lay_banner, null);

        hao_recycleview = (HaoRecyclerView) view.findViewById(R.id.hao_recycleview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        hao_recycleview.setLayoutManager(layoutManager);
        //添加Android自带的分割线
//        hao_recycleview.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL));

        //设置自定义加载中和到底了效果
        ProgressView progressView = new ProgressView(getActivity());
        progressView.setIndicatorId(ProgressView.BallPulse);
        progressView.setIndicatorColor(0xff69b3e0);
        hao_recycleview.setFootLoadingView(progressView);
//        TextView textView = new TextView(getActivity());
//        textView.setText("已经到底啦~");
//        hao_recycleview.setFootEndView(textView);

        switch (name) {
            case "商家优惠":
                ll_item.setVisibility(View.GONE);
                ll_item2.setVisibility(View.GONE);
                lv_item.removeHeaderView(headerview);
                lv_item.setAdapter(new MerchantsAdapter());
                break;
            case "招聘":
                ll_item2.setVisibility(View.GONE);
                intiCB();
                lv_item.removeHeaderView(headerview);
                lv_item.setAdapter(new RecruitmentAdapter());
                break;
            case "联盟":
                View rl_search = view.findViewById(R.id.rl_search);
                rl_search.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        listmerchant.clear();
                        page = 1;
                        GetMerchantList(et_search.getText().toString(), page);
                        et_search.setText("");
                        hao_recycleview.setCanloadMore(false);
                    }
                });
                lv_item.setVisibility(View.GONE);
                hao_recycleview.setVisibility(View.VISIBLE);
                ll_item.setVisibility(View.GONE);
//                GetBanner("SHOP");
                listmerchant.clear();
                page = 1;
                GetMerchantList("", page);
                unionAdapter = new UnionAdapter(getActivity(), listmerchant, listbanner);
                hao_recycleview.setAdapter(unionAdapter);
                hao_recycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        MerchantItem item = listmerchant.get(position);
//                        ToastUtils.getInstanc(getActivity()).showToast("商家id："+item.getId());
                        intent.putExtra("Merchantid", item.getId());
                        intent.setClass(getActivity(), MerchantDetailsActivity.class);
                        startActivity(intent);
                    }
                });
                hao_recycleview.setLoadMoreListener(new LoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        new Handler().postDelayed(new Runnable() {
                            public void run() {

                                page = page + 1;
                                GetMerchantList(et_search.getText().toString(), page);
                                hao_recycleview.loadMoreComplete();

                            }
                        }, 2000);
                    }
                });

                et_search = (EditText) view.findViewById(R.id.et_search);
                et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                    @Override
                    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                            listmerchant.clear();
                            page = 1;
                            GetMerchantList(et_search.getText().toString(), page);
                            et_search.setText("");
                            hao_recycleview.setCanloadMore(false);
//                            ToastUtils.getInstanc(getActivity()).showToast("搜索");
                        }
                        return false;
                    }
                });
                break;
            case "订单全部":
                ll_item.setVisibility(View.GONE);
                ll_item2.setVisibility(View.GONE);

                lv_item.setVisibility(View.GONE);
                hao_recycleview.setVisibility(View.VISIBLE);
                listorder.clear();
                page = 1;
                GetMineOrder(page);
                orderAdapter = new OrderAllAdapter(getActivity(), listorder);
                hao_recycleview.setAdapter(orderAdapter);
                hao_recycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        OrderItem item = listorder.get(position);
//                        ToastUtils.getInstanc(getActivity()).showToast("订单id："+item.getOrderId());
                        intent.putExtra("title", item.getSuitName());
                        intent.putExtra("orderId", item.getOrderId());
                        intent.setClass(getActivity(), MyOrderItemActivity.class);
                        startActivity(intent);
                    }
                });
                hao_recycleview.setLoadMoreListener(new LoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                page = page + 1;
                                GetMineOrder(page);
                                hao_recycleview.loadMoreComplete();

                            }
                        }, 2000);
                    }
                });
                break;
            case "订单待收货":
                ll_item.setVisibility(View.GONE);
                ll_item2.setVisibility(View.GONE);

//                lv_item.setAdapter(new OrderAllAdapter());
                break;
            case "消费与评价":
                ll_item.setVisibility(View.GONE);
                ll_item2.setVisibility(View.GONE);
//                lv_item.setAdapter(new OrderEvaAdapter());

                lv_item.setVisibility(View.GONE);
                hao_recycleview.setVisibility(View.VISIBLE);
                listordereva.clear();
                page = 1;
                GetMineEva(page);
                orderevaAdapter = new OrderEvaAdapter(getActivity(), listordereva);
                hao_recycleview.setAdapter(orderevaAdapter);
                hao_recycleview.setLoadMoreListener(new LoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                page = page + 1;
                                GetMineEva(page);
                                hao_recycleview.loadMoreComplete();

                            }
                        }, 2000);
                    }
                });

                break;
            case "联盟活动":
                ll_item.setVisibility(View.GONE);
                ll_item2.setVisibility(View.GONE);
                lv_item.removeHeaderView(headerview);
                listdir.addAll(JSONObject.parseArray(data, DirItem.class));
                lv_item.setAdapter(new DirAdapter());
                lv_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        intent.putExtra("id", listdir.get(position).getId());
                        intent.setClass(getActivity(), GoodsDetailsActivity.class);
                        startActivity(intent);
                    }
                });
                break;
            case "联盟优惠券":
                ll_item.setVisibility(View.GONE);
                ll_item2.setVisibility(View.GONE);
                lv_item.removeHeaderView(headerview);
                listcoupon.addAll(JSONObject.parseArray(data, CouponItem.class));
                lv_item.setAdapter(new CouponAdapter());
                lv_item.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        if (checkLogin()) return;
                        CouponItem data = listcoupon.get(position);
                        //进入优惠券
                        intent.putExtra("data", data);
                        intent.putExtra("coupon", "优惠券");
                        intent.setClass(getActivity(), CouponDetailsActivity.class);
                        startActivity(intent);
                    }
                });
                break;
            case "联盟套餐":
                ll_item.setVisibility(View.GONE);
                ll_item2.setVisibility(View.GONE);
//                lv_item.setAdapter(new OrderEvaAdapter());

                lv_item.setVisibility(View.GONE);
                hao_recycleview.setVisibility(View.VISIBLE);
                page = 1;
                GetSuit(page);
                suitAdapter = new SuitAdapter(getActivity(), listsuit);
                hao_recycleview.setAdapter(suitAdapter);
                hao_recycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        DirItem item = listsuit.get(position);
                        intent.putExtra("id", item.getId());
                        intent.setClass(getActivity(), GoodsDetailsActivity.class);
                        startActivity(intent);
                    }
                });
                hao_recycleview.setLoadMoreListener(new LoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                page = page + 1;
                                GetSuit(page);
                                hao_recycleview.loadMoreComplete();

                            }
                        }, 2000);
                    }
                });
                break;
            case "联盟预存":
                ll_item.setVisibility(View.GONE);
                ll_item2.setVisibility(View.GONE);
//                lv_item.setAdapter(new OrderEvaAdapter());

                lv_item.setVisibility(View.GONE);
                hao_recycleview.setVisibility(View.VISIBLE);
                page = 1;

                GetPrestoreList(page);
//                suitAdapter = new SuitAdapter(getActivity(), listsuit);
                prestoreAdapter = new PrestoreAdapter(getActivity(), listprestore);
                hao_recycleview.setAdapter(prestoreAdapter);
                hao_recycleview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        PrestoreItem item = listprestore.get(position);
//                        ToastUtils.getInstanc(getActivity()).showToast("商家id："+item.getId());
                        intent.putExtra("prestoreId", item.getId());
                        intent.setClass(getActivity(), PrestoreDetailsActivity.class);
                        startActivity(intent);
                    }
                });
                hao_recycleview.setLoadMoreListener(new LoadMoreListener() {
                    @Override
                    public void onLoadMore() {
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                page = page + 1;
                                GetPrestoreList(page);
                                hao_recycleview.loadMoreComplete();

                            }
                        }, 2000);
                    }
                });
                break;
        }
    }

    /**
     * 获取预存活动列表
     */
    private void GetPrestoreList(int page) {
        String url = API.GetPrestoreList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数

        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addFormDataPart("lat", StartActivity.mLatitude + "");
        params.addFormDataPart("log", StartActivity.mLongitude + "");
        params.addFormDataPart("userId", MainActivity.userid);
        params.addFormDataPart("merchantId", data);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
//
                    if (listprestore.size() == totalCount)//总个数已满
                    {
                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(getActivity()).showToast("暂无更多");
                    } else {
                        listprestore.addAll(JSONObject.parseArray(data.getString("prestoreList"), PrestoreItem.class));
                        prestoreAdapter.notifyDataSetChanged();
                    }
                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 评价完刷新消费与评价
     */
    public void refresheva() {
        listordereva.clear();
        page = 1;
        GetMineEva(page);
        hao_recycleview.loadMoreComplete();
    }


    @Override
    public void onResume() {
        super.onResume();

        if (!MainActivity.mobile.equals("")) {
            isLogin = true;
        } else {
            isLogin = false;
        }
    }


    /**
     * 校验登录状态
     *
     * @return
     */
    private boolean checkLogin() {
        // 如果未登录都进入登录界面
        if (!isLogin) {
            intent.setClass(getActivity(), LoginPhoneActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    /**
     * 消费与评价列表
     *
     * @param page
     */
    private void GetMineEva(int page) {
        String url = API.GetMineEva + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listordereva.size() == totalCount)//总个数已满
                    {
                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(getActivity()).showToast("暂无更多");
                    } else {
                        listordereva.addAll(JSONObject.parseArray(data.getString("consumeList"), OrderEvaItem.class));
                        orderevaAdapter.notifyDataSetChanged();
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
                        intent.setClass(getActivity(), LoginPhoneActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                    } else {
                        ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                    }
                }
            }


            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 商家套餐列表
     *
     * @param page
     */
    private void GetSuit(int page) {
        String url = API.GetSuit + data;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
//        params.addHeader("token", MainActivity.token);//添加header信息
        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addFormDataPart("merchantId", data);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listsuit.size() == totalCount)//总个数已满
                    {
                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(getActivity()).showToast("暂无更多");
                    } else {
                        listsuit.addAll(JSONObject.parseArray(data.getString("suitList"), DirItem.class));
                        suitAdapter.notifyDataSetChanged();
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
//                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
                        intent.setClass(getActivity(), LoginPhoneActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                    } else {
                        ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                    }
                }
            }


            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 直营
     */
    class DirAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listdir.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DirItem item = listdir.get(position);

            View view = getLayoutInflater().inflate(R.layout.lv_directly_item, null);
            TextView tv_original = (TextView) view.findViewById(R.id.tv_original);
//            tv_original.setText(MyUtils.getdouble(item.getOriginalPrice()));
            tv_original.setText(item.getOriginalPrice() + "");
            tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线
            ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);
            Picasso.with(getActivity()).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_item);
            TextView tv_price = (TextView) view.findViewById(R.id.tv_price);
//            tv_price.setText(MyUtils.getdouble(item.getPrice()));
            tv_price.setText(item.getPrice() + "");
            TextView tv_sales = (TextView) view.findViewById(R.id.tv_sales);
            tv_sales.setText("销量：" + item.getSales());
            TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
            tv_title.setText(item.getName());
            TextView tv_giving = (TextView) view.findViewById(R.id.tv_giving);
            if (item.getCouponLimit() == 0) {
                tv_giving.setText("");
            } else {
                tv_giving.setText("最高抵扣" + (item.getCouponLimit() * 10) + "元");
            }

//            StringBuffer sb = new StringBuffer();
//            sb.append("赠送：");
//            for (int i = 0; i < item.getProjectList().size(); i++) {
//                ProjectList projectitem = item.getProjectList().get(i);
//                if (projectitem.isGiving()) {
//                    sb.append(projectitem.getProjectName() + projectitem.getNum() + "次");
//                }
//            }
//            tv_giving.setText(sb.toString());
            return view;
        }
    }

    /**
     * 联盟优惠券
     */
    class CouponAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return listcoupon.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            CouponItem item = listcoupon.get(position);
            View view = getLayoutInflater().inflate(R.layout.lv_coupons_item, null);
            TextView tv_name = (TextView) view.findViewById(R.id.tv_name);
            tv_name.setText(item.getName());
            TextView tv_time = (TextView) view.findViewById(R.id.tv_time);
            tv_time.setText("有效至：" + item.getEndTime());
            TextView tv_merchantName = (TextView) view.findViewById(R.id.tv_merchantName);
            tv_merchantName.setText(item.getMerchantName());
            TextView tv_inventory = (TextView) view.findViewById(R.id.tv_inventory);
            tv_inventory.setText("剩余数量：" + item.getInventory());
            ImageView iv_item = (ImageView) view.findViewById(R.id.iv_item);
            Picasso.with(getActivity()).load(item.getUrl()).error(R.mipmap.ic_loadingerror).into(iv_item);
            TextView tv_distance = (TextView) view.findViewById(R.id.tv_distance);
            tv_distance.setVisibility(View.GONE);
//            intiDistance(tv_distance, item);
            return view;
        }
    }


    /**
     * 距离计算
     *
     * @param
     * @param item
     */
    private void intiDistance(TextView tv, CouponItem item) {
        LatLng startLatlng = new LatLng(StartActivity.mLatitude, StartActivity.mLongitude);
        LatLng endLatlng = new LatLng(Double.valueOf(item.getLatitude()), Double.valueOf(item.getLongitude()));

        double distance = AMapUtils.calculateLineDistance(startLatlng, endLatlng);
        distance = distance / 1000;
        DecimalFormat df = new DecimalFormat("0.##");
        String st = df.format(distance);
        tv.setText(st + "km");
    }


    /**
     * 获取我的订单全部
     */
    private void GetMineOrder(int page) {
        String url = API.GetMineOrder + page + "/10" + "/" + MainActivity.userid;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addHeader("token", MainActivity.token);//添加header信息
//        params.addFormDataPart("page", page);
//        params.addFormDataPart("pageSize", 10);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listorder.size() == totalCount)//总个数已满
                    {
                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(getActivity()).showToast("暂无更多");
                    } else {
                        listorder.addAll(JSONObject.parseArray(data.getString("orderList"), OrderItem.class));
                        orderAdapter.notifyDataSetChanged();
                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    if (data.getString("code").equals("401") || data.getString("code").equals("400")) {
                        intent.setClass(getActivity(), LoginPhoneActivity.class);
                        startActivity(intent);
                        getActivity().finish();
                    } else {
                        ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                    }
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 获取商家列表
     */
    private void GetMerchantList(String name, int page) {
        String url = API.GetMerchantList;
        RequestParams params = new RequestParams(new MyHttpCycleContext());//请求参数
        params.addFormDataPart("name", name);
        params.addFormDataPart("page", page);
        params.addFormDataPart("pageSize", 10);
        params.addFormDataPart("lat", StartActivity.mLatitude + "");
        params.addFormDataPart("log", StartActivity.mLongitude + "");
        params.addFormDataPart("userId", MainActivity.userid);

        HttpRequest.get(url, params, new BaseHttpRequestCallback<String>() {

            //请求网络前
            @Override
            public void onStart() {
                showdialog();
            }

            @Override
            protected void onSuccess(String str) {
                Log.e("==", str);
                JSONObject json = JSONObject.parseObject(str);
                if (json.getBoolean("successful")) {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    totalCount = data.getInteger("totalCount");
                    if (listmerchant.size() == totalCount)//总个数已满
                    {
                        hao_recycleview.setCanloadMore(false);
                        ToastUtils.getInstanc(getActivity()).showToast("暂无更多");
                    } else {
                        listmerchant.addAll(JSONObject.parseArray(data.getString("merchantList"), MerchantItem.class));
                        unionAdapter.notifyDataSetChanged();
                    }
//                    if(JSONObject.parseArray(data.getString("merchantList"), MerchantItem.class).size()==0)
//                    {
//                        hao_recycleview.setCanloadMore(false);
//                    }

                } else {
                    String datastr = json.getString("data");
                    JSONObject data = JSONObject.parseObject(datastr);
                    ToastUtils.getInstanc(getActivity()).showToast(data.getString("msg"));
                }
            }

            //请求失败（服务返回非法JSON、服务器异常、网络异常）
            @Override
            public void onFailure(int errorCode, String msg) {
//                toast("网络异常~，请检查你的网络是否连接后再试");
                Log.e("==", msg);
            }

            //请求网络结束
            @Override
            public void onFinish() {
                dismissdialog();
            }
        });
    }


    /**
     * 初始化首页banner
     */
    private void intiBanner() {
        Banner banner = (Banner) headerview.findViewById(R.id.banner);
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new BannerLoader());
        //设置图片集合
        banner.setImages(listbanner);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.Default);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }


    /**
     * 初始化cb （排序功能）
     */
    private void intiCB() {
        cb_1 = (CheckBox) view.findViewById(R.id.cb_1);
        cb_1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                CheckBox cb = (CheckBox) buttonView;
                Drawable up_red = getResources().getDrawable(R.mipmap.ic_red_up);
                Drawable down_red = getResources().getDrawable(R.mipmap.ic_red_down);
                up_red.setBounds(0, 0, up_red.getMinimumWidth(), up_red.getMinimumHeight());
                down_red.setBounds(0, 0, down_red.getMinimumWidth(), down_red.getMinimumHeight());
                if (isChecked) {
                    cb.setCompoundDrawables(null, null, up_red, null);
                } else {
                    cb.setCompoundDrawables(null, null, down_red, null);
                }


            }
        });
        cb_2 = (CheckBox) view.findViewById(R.id.cb_2);
        cb_2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                CheckBox cb = (CheckBox) buttonView;
                Drawable up_gray = getResources().getDrawable(R.mipmap.ic_gray_up);
                Drawable down_gray = getResources().getDrawable(R.mipmap.ic_gray_down);
                up_gray.setBounds(0, 0, up_gray.getMinimumWidth(), up_gray.getMinimumHeight());
                down_gray.setBounds(0, 0, down_gray.getMinimumWidth(), down_gray.getMinimumHeight());
                if (isChecked) {
                    cb.setCompoundDrawables(null, null, up_gray, null);
                } else {
                    cb.setCompoundDrawables(null, null, down_gray, null);
                }
            }
        });
    }


    class MerchantsAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return size;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = inflater.inflate(R.layout.lv_home_item, null);

            TextView tv_original = (TextView) view.findViewById(R.id.tv_original);
            tv_original.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);//添加下划线
            return view;
        }
    }


    class RecruitmentAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return size;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.lv_recruitment_item, null);
            return view;
        }
    }


    @Override
    public void onStart() {
        super.onStart();
//        IntentFilter myIntentFilter = new IntentFilter();
//        myIntentFilter.addAction("MerchantList");
//        //注册广播
//        getActivity().registerReceiver(new MyReceiver(), myIntentFilter);
    }

//    class MyReceiver extends BroadcastReceiver {
//
//       boolean issec=false;
//        Handler handler=new Handler();
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if(issec){
//                return;
//            }else {
//                issec=true;
//                hao_recycleview.setCanloadMore(true);
//                listmerchant.clear();
//                unionAdapter.notifyDataSetChanged();
//                page = 1;
//                GetMerchantList("", page);
//            }
//            handler.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    issec=false;
//                }
//            },2000);
//
//
//        }
//    }

    public void fresh() {
        hao_recycleview.setCanloadMore(true);
        listmerchant.clear();
        unionAdapter.notifyDataSetChanged();
        page = 1;
        GetMerchantList("", page);
    }

}
